/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.digitalization.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.digitalization.entity.*;
import org.springblade.modules.digitalization.mapper.B01Mapper;
import org.springblade.modules.digitalization.node.ForestNodeMerger;
import org.springblade.modules.digitalization.service.IA01Service;
import org.springblade.modules.digitalization.service.IA02Service;
import org.springblade.modules.digitalization.service.IB01Service;
import org.springblade.modules.digitalization.service.IManageArchivesService;
import org.springblade.modules.digitalization.utils.B01UpLoad;
import org.springblade.modules.digitalization.utils.DictListener;
import org.springblade.modules.digitalization.vo.B01VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 单位基本情况信息集-JAVA 服务实现类
 *
 * @author RS
 * @since 2022-10-18
 */
@Service
public class B01ServiceImpl extends BaseServiceImpl<B01Mapper, B01Entity> implements IB01Service {

	@Autowired
	private IA01Service a01Service;
	@Autowired
	private IA02Service a02Service;
	@Autowired
	private IManageArchivesService manageArchivesService;

	@Override
	public IPage<B01VO> selectB01Page(IPage<B01VO> page, B01VO b01) {
		return page.setRecords(baseMapper.selectB01Page(page, b01));
	}


	@Override
	public List<B01VO> tree(String tenantId) {
		return tree(tenantId, null);
	}


	public List<Long> getAuthedB01Ids() {
		Long userId = AuthUtil.getUserId();
		List<AuthB01Entity> datas = authB01Service.findByUserId(userId);
		if (datas.isEmpty()) {
			datas = authB01Service.findByDeptIds(AuthUtil.getDeptId());
		}
		return datas.stream().map(AuthB01Entity::getB01Id).distinct().collect(Collectors.toList());
	}

	private List<B01VO> findNodes(List<B01VO> nodes, List<Long> ids) {
		List<B01VO> foundNodes = Lists.newArrayList();
		for (B01VO node : nodes) {
			if (node.getChildren() == null) {
				node.setChildren(Lists.newArrayList());
			}
			if (ids.contains(node.getId())) {
				B01VO newNode = new B01VO();
				Func.copy(node, newNode);
				newNode.setDisabled(false);
				newNode.setChildren(findNodes(newNode.getChildren(), ids));
				foundNodes.add(newNode);
			} else {
				List<B01VO> result = findNodes(node.getChildren(), ids);
				if (!result.isEmpty()) {
					B01VO newNode = new B01VO();
					Func.copy(node, newNode);
					newNode.setDisabled(true);
					newNode.setChildren(result);
					foundNodes.add(newNode);
				}
			}
		}
		return foundNodes;
	}

	@Autowired
	private AuthB01ServiceImpl authB01Service;


	@Override
	public List<B01VO> treeWithAuth(String tenantId) {
		List<B01VO> tree = tree(tenantId);
		List<B01VO> authedTree = findNodes(tree, getAuthedB01Ids());
		return authedTree;
	}

	@Override
	public List<B01VO> tree(String tenantId, List<Long> deptIds) {
		return ForestNodeMerger.merge(baseMapper.tree(tenantId, deptIds));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R upload(MultipartFile file) {
		//读取文件内容
		DictListener dictListener = new DictListener();
		try {
			EasyExcel.read(file.getInputStream(), B01UpLoad.class, dictListener).sheet().doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//转换为b01
		List<B01UpLoad> upLoads = dictListener.getUpLoads();
		if (Func.isEmpty(upLoads)) {
			throw new ServiceException("文件数据为空");
		}
		List<B01Entity> daB01List = new ArrayList<>();
		String id = "";
		int sortid = 0;

		//检索出根节点
		int genlenth = 0;
		String genb0111 = "";
		for (B01UpLoad upLoad : upLoads) {
			if (genlenth == 0 || genlenth > upLoad.getB0111s().length()) {
				genlenth = upLoad.getB0111s().length();
				genb0111 = upLoad.getB0111s();
			}
		}

		for (B01UpLoad upLoad : upLoads) {
			B01Entity daB01 = new B01Entity();
			id = autoid(id);
			daB01.setId(Long.parseLong(id));
			//001001转为001.001
			upLoad.setB0111s(b0111zhuan(upLoad.getB0111s()));
			daB01.setB0111(upLoad.getB0111s());
			System.err.println(upLoad.getB0111s());
			String b0121 = upLoad.getB0111s();
			boolean isgen = false;
			if (upLoad.getB0111s().length() > 3)
				b0121 = upLoad.getB0111s().substring(0, upLoad.getB0111s().length() - 4);

			if (upLoad.getB0111s().equals(genb0111)) {
				daB01.setB0121("0");
			} else {
				daB01.setB0121(b0121);
			}

			daB01.setB0101(upLoad.getB0101());
			daB01.setB0104(upLoad.getB0101());
			daB01.setB0194(upLoad.getB0194());
			daB01.setB0124(upLoad.getB0124());
			daB01.setB0131(upLoad.getB0131());
			daB01.setB0127(upLoad.getB0127());
			daB01.setSortid((sortid++) + "");
			daB01.setCreateDept(Long.parseLong(id));
			daB01.setTenantId("000000");
			daB01List.add(daB01);
		}
		//清空b01
		baseMapper.deleteall();
		//添加到b01
		boolean saveBatch = this.saveBatch(daB01List);
//		B01System system = new B01System(dataSource, this, deptService);
//		system.dab01system();
//
//		//给超管添加机构id
//		DaB01 dab01 =baseMapper.selectOne(new QueryWrapper<DaB01>().select("id").isNotNull("b0121").orderByAsc("b0121").last("limit 1"));
//		userService.update(new LambdaUpdateWrapper<User>().set(User::getDeptId,dab01.getId()).eq(User::getTenantId, BladeConstant.ADMIN_TENANT_ID));
//		tenantService.update(new LambdaUpdateWrapper<Tenant>().set(Tenant::getDeptId,dab01.getId()).eq(Tenant::getTenantId,BladeConstant.ADMIN_TENANT_ID));
//
//		//拼音初始化
//		List<DaB01> daB01s = baseMapper.selectList(null);
//
//		daB01s.forEach(daB01 -> b01PinYinService.save(new B01PinYin(daB01.getId(), PinYinUtil.getFirstPinYin(daB01.getB0104()))));
//

		return R.success("导入完成");
	}

	@Override
	public List<B01VO> dictory() {
		return this.baseMapper.tree("000000", null);
	}

	@Override
	public List<B01Entity> path(String tenantId, String deptCode) {
		List<B01Entity> objects = Lists.newArrayList();
		B01Entity b01Entity;
		do {
			b01Entity = findOne(tenantId, deptCode);
			if (b01Entity != null) {
				objects.add(0, b01Entity);
				if (StringUtil.equals(b01Entity.getB0121(), "0") == false) {
					deptCode = b01Entity.getB0121();
				} else {
					break;
				}
			}
		} while (b01Entity != null);
		return objects;
	}

	@Transactional
	@Override
	public boolean update(B01Entity b01) {
		B01Entity oldB01Entity = getById(b01.getId());
		this.updateById(b01);
		// 如果编号发生更改，更新关联表
		if (StringUtil.equals(oldB01Entity.getB0111(), b01.getB0111()) == false) {
			a01Service.update(Wrappers.<A01Entity>lambdaUpdate()
				.eq(A01Entity::getA0195, oldB01Entity.getB0111())
				.set(A01Entity::getA0195, b01.getB0111()));

			a02Service.update(Wrappers.<A02Entity>lambdaUpdate()
				.eq(A02Entity::getA0201b, oldB01Entity.getB0111())
				.set(A02Entity::getA0201b, b01.getB0111()));

			manageArchivesService.update(Wrappers.<ManageArchivesEntity>lambdaUpdate()
				.eq(ManageArchivesEntity::getB0111, oldB01Entity.getB0111())
				.set(ManageArchivesEntity::getB0111, b01.getB0111()));
		}
		return true;
	}

	private B01Entity findOne(String tenantId, String deptCode) {
		LambdaQueryWrapper<B01Entity> query = Wrappers.<B01Entity>lambdaQuery().eq(B01Entity::getB0111, deptCode)
			.eq(B01Entity::getTenantId, tenantId);
		try {
			B01Entity b01Entity = this.baseMapper.selectOne(query);
			return b01Entity;
		} catch (Exception e) {
			return null;
		}
	}


	public String autoid(String oldformat) {
		if (!oldformat.equals("")) {
			Long id = Long.parseLong(oldformat);
			return (++id).toString();
		}
		SimpleDateFormat date = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String newb0111;//=date.format(new Date(System.currentTimeMillis()));
		do {
			newb0111 = date.format(new Date(System.currentTimeMillis()));

		} while (oldformat.equals(newb0111));
		System.out.println("当前时间：" + newb0111);
		return newb0111;
	}

	private String b0111zhuan(String b0121) {
		if (b0121.length() > 3) {
			int isgeshi = b0121.indexOf(".");
			if (isgeshi == -1) {
				String zifu[] = b0121.split("");
				b0121 = "";
				for (int i = 0; i < zifu.length; i++) {
					b0121 += zifu[i];
					if ((i + 1) % 3 == 0 && i != zifu.length - 1) {
						b0121 += ".";
					}
				}
			}
		}
		return b0121;
	}
}
